/**
 * version 1.0
 * User: johnny zyc
 * Date: 13-6-27
 * Time: 下午10:36
 * To change this template use File | Settings | File Templates.
 *
 * 自动生成选择select，最多三级选择
 *
 * 用法： $('#city_select').area(['province', 'city']);
 *
 * province和city分别是对应select的name，最多可以设置三个
 */
(function ($) {
	$.fn.area = function (names) {
		fn.generalSelect(this, names);
		fn.initData(names[0]);
	}

	var fn = {
		bingChange: function (_this) {
			var value = $(_this).val();
			if ($(_this).next('select').length > 0) {
				var index_ele = $(_this).next('select');
				fn.changeData(index_ele, value);
				while ($(index_ele).next('select').length > 0) {
					var next_ele = $(index_ele).next('select');
					fn.resetSelect(next_ele);
					index_ele = next_ele;
				}
			}
		},
		changeData: function (_this, parent) {
			var data = fn.getRemoteArea(parent);
			var option_first = _this.find('option')[0];
			_this.html(option_first);
			$.each(data, function (n, d) {
				var option = '<option value="' + d.id + '">' + d.name + '</option>'
				_this.append(option);
			})
		},
		resetSelect: function (_this) {
			var target = $('select[name="' + $(_this).attr('name') + '"]');
			var option_first = target.find('option')[0];
			target.html(option_first);
		},
		getRemoteArea: function (parent) {
			var temp;
			$.ajax({
				url: '/area/' + parent,
				async: false,
				success: function (data) {
					temp = data.area;
				}
			});
			return temp;
		},
		generalSelect: function (container, names) {
			$.each(names, function (index, name) {
				if (index < 3) {
					var ele = '<select class="ui-select" name="' + name + '">';
					ele += '<option value="0">请选择' + label[index] + '</option>';
					ele += '</select>&nbsp;&nbsp;';
					container.append(ele);
					$('select[name="' + name + '"]').live('change', function () {
						fn.bingChange(this);
					});
				}
			})
		},
		initData: function (root) {
			var data = fn.getRemoteArea(0);
			$.each(data, function (n, d) {
				var option = '<option value="' + d.id + '">' + d.name + '</option>'
				$('select[name="' + root + '"]').append(option);
			})
		}
	}

	var label = ['省份/直辖市', '市', '地级市/区']

//		yemian

})(jQuery);